package com.xyp.iodemo.nettyrpcclient.netty;

import com.xyp.iodemo.nettyrpcclient.interfaces.INettyCallBack;
import com.xyp.iodemo.nettyrpccommon.model.RPCNetty;
import com.xyp.iodemo.nettyrpccommon.utils.JsonMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.logging.Logger;

/**
 * @author xuyuanpeng
 * @version 1.0
 * @date 2019-03-06 17:40
 */
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private static java.util.logging.Logger logger = Logger.getLogger("EchoClientHandler");

    private RPCNetty rpcNetty;
    private INettyCallBack nettyCallBack;
    public EchoClientHandler(RPCNetty rpcNetty,INettyCallBack nettyCallBack){
        this.rpcNetty=rpcNetty;
        this.nettyCallBack=nettyCallBack;
    }

    public RPCNetty getRpcNetty() {
        return rpcNetty;
    }

    public void setRpcNetty(RPCNetty rpcNetty) {
        this.rpcNetty = rpcNetty;
    }

    public INettyCallBack getNettyCallBack() {
        return nettyCallBack;
    }

    public void setNettyCallBack(INettyCallBack nettyCallBack) {
        this.nettyCallBack = nettyCallBack;
    }

    public EchoClientHandler(){}

    /**
     * 请求数据
     * @param context
     */
    @Override
    public void channelActive(ChannelHandlerContext context){
        logger.info("client channelActive >>"+ JsonMapper.toJsonString(rpcNetty));
        context.writeAndFlush(Unpooled.copiedBuffer(JsonMapper.toJsonString(rpcNetty),
                CharsetUtil.UTF_8));
    }

    /**
     * 服务器返回数据
     * @param context
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext context, ByteBuf byteBuf) throws Exception {
        logger.info("client channelRead0 >>"+byteBuf.toString(CharsetUtil.UTF_8));

//        XLogUtils.error("Client received",byteBuf.toString(CharsetUtil.UTF_8));
        nettyCallBack.calllBack(byteBuf.toString(CharsetUtil.UTF_8));
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
